import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/smart_warehouse/product_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/smart_warehouse/product_storage_d_t_o_entity.dart';
import 'package:flutter/services.dart';

/// 新添加产品页面
class NewAddProductDialog extends StatefulWidget {
  const NewAddProductDialog({
    required this.num,
    required this.type,
    required this.warehouseId,
    required this.id,
    super.key,
  });

  final int num; // 本次入库数据
  final int type; // 出入库类型 0:入库 1:出库
  final String warehouseId; //仓库id
  final String id; //产品列表数据id

  @override
  State<NewAddProductDialog> createState() => _NewAddProductDialogState();
}

class _NewAddProductDialogState extends State<NewAddProductDialog> {
  int toBeStoredNum = 0; // 添加到仓库产品的数量
  List<ProductEntity> productList = []; // 产品列表
  List<ProductStorageDTOEntity> selectedProductList = []; // 选中的产品数据

  @override
  void initState() {
    super.initState();
    toBeStoredNum = widget.num;
    _getWarehouseList();
  }

  //获取智慧仓储产品存储量列表
  _getWarehouseList() async {
    // 获取仓库列表
    final res = await HttpUtil().generatePostRequest<List<ProductEntity>>(
      Interface.getProductByPage,
      data: {
        'pageNum': 1,
        'pageSize': 1000,
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        productList = result.data!;
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        type: MaterialType.transparency, //透明类型
        child: Container(
            color: Colors.transparent,
            alignment: Alignment.center,
            child: Container(
              alignment: Alignment.center,
              width: 320.w,
              height: 450.w,
              padding: EdgeInsets.only(top: 15.w),
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(20.r))),
              child: Column(
                children: [
                  Text(
                    '产品${widget.type == 0 ? '入库' : '出库'}',
                    style: TextStyle(color: const Color(0xff000000), fontSize: 16.w, fontWeight: FontWeight.w500),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 20.w, left: 15.w, right: 15.w),
                    child: _getProductName(),
                  ),
                  SizedBox(height: 10.w),
                  Expanded(
                      child: SingleChildScrollView(
                    child: Column(
                      children: selectedProductList.map((item) {
                        final TextEditingController textController = TextEditingController(text: item.inventory.toString());
                        textController.selection = TextSelection.fromPosition(TextPosition(offset: textController.text.length));

                        return Container(
                          decoration: BoxDecoration(
                              color: const Color(0xffFFFFFF),
                              border: Border.all(color: const Color(0xff3074FF), width: 1.w),
                              borderRadius: BorderRadius.all(Radius.circular(4.w))),
                          margin: EdgeInsets.only(left: 15.w, right: 15.w, bottom: 10.w),
                          padding: EdgeInsets.only(left: 5.w, top: 10.w, bottom: 10.w, right: 5.w),
                          child: Row(
                            children: [
                              Container(
                                margin: EdgeInsets.only(right: 5.w),
                                alignment: Alignment.center,
                                width: 27.w,
                                height: 27.w,
                                decoration: BoxDecoration(
                                    color: const Color(0xfff14943),
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(90.r),
                                    )),
                                child: Text(
                                  '移除',
                                  style: TextStyle(
                                    color: const Color(0xffffffff),
                                    fontSize: 10.sp,
                                    fontWeight: FontWeight.w400,
                                  ),
                                ),
                              ).clickOnce(() {
                                selectedProductList.remove(item);
                                toBeStoredNum += item.inventory;
                                setState(() {});
                              }),
                              Expanded(
                                child: Text(
                                  item.productName,
                                  style: TextStyle(
                                    color: const Color(0xff000000),
                                    fontSize: 15.w,
                                    fontWeight: FontWeight.w400,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                                  children: [
                                    // 减少按钮
                                    Container(
                                      alignment: Alignment.center,
                                      width: 27.w,
                                      height: 27.w,
                                      decoration: BoxDecoration(
                                          color: const Color(0xffF2F2F2),
                                          borderRadius: BorderRadius.all(
                                            Radius.circular(90.r),
                                          )),
                                      child: Text(
                                        '-',
                                        style: TextStyle(
                                          color: const Color(0xff000000),
                                          fontSize: 15.w,
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                    ).clickOnce(() {
                                      if (item.inventory <= 1) {
                                        return;
                                      }
                                      toBeStoredNum++;
                                      setState(() {
                                        item.inventory--;
                                      });
                                    }),
                                    SizedBox(
                                      width: 20.w,
                                      child: TextField(
                                        keyboardType: TextInputType.number,
                                        inputFormatters: [
                                          //数字，只能是整数
                                          FilteringTextInputFormatter.digitsOnly,
                                          //限制长度
                                          LengthLimitingTextInputFormatter(2),
                                        ],
                                        textInputAction: TextInputAction.done,
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          fontWeight: FontWeight.w400,
                                          fontSize: 12.w,
                                          color: const Color(0xff333333),
                                        ),
                                        onChanged: (value) {
                                          // 先将之前存在的数量还给总数
                                          toBeStoredNum += item.inventory;
                                          // 如果为空，则设置为1
                                          if (value.isEmpty) {
                                            item.inventory = 1;
                                            toBeStoredNum -= 1;
                                            // setState(() {});
                                            return;
                                          }
                                          final inventory = int.parse(value);
                                          // 输入的值小于或等于总数
                                          if (inventory <= toBeStoredNum) {
                                            item.inventory = inventory;
                                            toBeStoredNum -= inventory;
                                          } else {
                                            item.inventory = toBeStoredNum;
                                            toBeStoredNum = 0;
                                          }
                                          setState(() {});
                                        },
                                        controller: textController,
                                        decoration: InputDecoration(
                                          //防止适配不居中
                                          isCollapsed: true,
                                          border: const OutlineInputBorder(borderSide: BorderSide.none),
                                          hintStyle: TextStyle(
                                            fontWeight: FontWeight.w400,
                                            fontSize: 12.w,
                                            color: const Color(0xff333333),
                                          ),
                                        ),
                                        maxLines: 1,
                                        minLines: 1,
                                      ),
                                    ),
                                    // 数量显示
                                    // SizedBox(
                                    //   width: 20.w,
                                    //   child: Text(
                                    //     item.inventory.toString(),
                                    //     textAlign: TextAlign.center,
                                    //     style: TextStyle(
                                    //       fontWeight: FontWeight.w400,
                                    //       fontSize: 12.w,
                                    //       color: const Color(0xff333333),
                                    //     ),
                                    //   ),
                                    // ),
                                    // 增加按钮
                                    Container(
                                      alignment: Alignment.center,
                                      width: 27.w,
                                      height: 27.w,
                                      decoration: BoxDecoration(
                                          color: const Color(0xffF2F2F2),
                                          borderRadius: BorderRadius.all(
                                            Radius.circular(90.r),
                                          )),
                                      child: Text(
                                        '+',
                                        style: TextStyle(
                                          color: const Color(0xff000000),
                                          fontSize: 15.w,
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                    ).clickOnce(() {
                                      if (toBeStoredNum <= 0) {
                                        AppToast.showWarning('数量不足!');
                                        return;
                                      }
                                      toBeStoredNum--;
                                      setState(() {
                                        item.inventory++;
                                      });
                                    }),
                                  ],
                                ),
                              )
                            ],
                          ),
                        );
                      }).toList(),
                    ),
                  )),
                  _getBottomButtonWidget(),
                ],
              ),
            )));
  }

  //获取产品名称显示
  Widget _getProductName() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              '待${widget.type == 0 ? '入库' : '出库'}数量',
              style: TextStyle(color: const Color(0xff000000), fontSize: 14.w, fontWeight: FontWeight.w500),
            ),
            Expanded(
              child: Text(
                '$toBeStoredNum',
                textAlign: TextAlign.right,
                style: TextStyle(
                  color: const Color(0xff000000),
                  fontSize: 14.w,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ],
        ),
        AppGaps.vGap10,
        Container(
          decoration: BoxDecoration(
              color: const Color(0xffFFFFFF),
              border: Border.all(color: const Color(0xff000000).withOpacity(0.1), width: 1.w),
              borderRadius: BorderRadius.all(Radius.circular(4.w))),
          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 9.w),
          child: Row(
            children: [
              Expanded(
                  child: Text(
                '请选择产品',
                style: TextStyle(height: 1.2, color: const Color(0xff262F38), fontSize: 14.w, fontWeight: FontWeight.w400),
              )),
              Icon(
                Icons.expand_more,
                size: 15.w,
                color: const Color(0xffA0A7B5),
              ),
            ],
          ),
        ).clickOnce(() {
          CustomSelectFunction.selectMultipleBottomSheet<ProductEntity>(
            title: '选择产品',
            dataList: productList,
            checkedList: [],
            isMultiple: false,
            onCallBack: (value) {
              final item = value.first;
              if (toBeStoredNum <= 0) {
                AppToast.showWarning('数量不足!');
                return;
              }
              toBeStoredNum--;
              final productBean = ProductStorageDTOEntity()
                ..inventory = 1
                ..productName = item.getShowName()
                ..productId = item.getId()
                ..warehouseId = widget.warehouseId;
              selectedProductList.add(productBean);
              setState(() {});
            },
          );
        }),
      ],
    );
  }

  //获取底部按钮显示
  Widget _getBottomButtonWidget() {
    return Column(
      children: [
        Container(
          height: 1.w,
          color: const Color(0xffF2F2F2),
        ),
        Row(
          children: [
            Expanded(
                child: Container(
                    color: Colors.transparent,
                    alignment: Alignment.center,
                    child: Text(
                      '取消',
                      style: TextStyle(color: const Color(0xff7F8A9C), fontSize: 14.w, fontWeight: FontWeight.w400),
                    )).clickOnce(Get.back)),
            Container(
              height: 48.w,
              width: 1.w,
              color: const Color(0xffF2F2F2),
            ),
            Expanded(
                child: Container(
                    color: Colors.transparent,
                    alignment: Alignment.center,
                    child: Text(
                      '确定',
                      style: TextStyle(color: const Color(0xff3074FF), fontSize: 14.w, fontWeight: FontWeight.w400),
                    )).clickOnce(() {
              if (selectedProductList.isEmpty) {
                AppToast.showWarning('选择产品!');
                return;
              }
              startInWarehouse();
            })),
          ],
        )
      ],
    );
  }

  //提交出入库
  startInWarehouse() async {
    final res = await HttpUtil()
        .generatePostRequest(
          widget.type == 0 ? Interface.productStorage : Interface.productOutbound,
          data: selectedProductList,
        )
        .execute();
    res.onSuccess((result) {
      deleteList();
    });
  }

  // 删除列表
  deleteList() async {
    final res = await HttpUtil().generateDeleteRequest('${Interface.delWarehousing}/${widget.id}').execute();
    res.onSuccess((result) {
      Get.back();
      AppToast.showWarning('提交成功!');
    });
  }
}
